package evolution;

import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

import evolution.Directory;
import evolution.File;
import evolution.Resource;
import evolution.ResourceVisitor;


public class StubDirectory implements Directory
{
	private final Map<String, Resource> members = new HashMap<String, Resource>();
	private final String name;
	private Directory parent;
	private long lastModified;
	private final TimeKeeper timeKeeper;

	public StubDirectory(String name, TimeKeeper timeKeeper)
	{
		this.name = name;
		this.timeKeeper = timeKeeper;
		this.lastModified = timeKeeper.currentTime();
	}

	public void addMember(Resource resource)
	{
		members.put(resource.getName(), resource);
		resource.setParent(this);
		lastModified = timeKeeper.currentTime();
	}

	public Resource getMember(String name)
	{
		return members.get(name);
	}

	public String getName()
	{
		return name;
	}

	public void deleteMember(String name)
	{
		members.remove(name);
	}

	public Iterator<Resource> iterator()
	{
		return members.values().iterator();
	}

	public void setParent(Directory parent)
	{
		this.parent = parent;
	}

	public String getPath()
	{
		if (parent != null)
		{
			String parentPath = parent.getPath();
			if (parentPath.equals("/"))
			{
				return "/" + getName();
			}
			else
			{
				return parentPath + "/" + getName();
			}
		}
		else
		{
			return getName();
		}
	}

	public long getLastModifiedTime()
	{
		return lastModified;
	}

	public void accept(ResourceVisitor visitor)
	{
		visitor.visitDirectory(this);
		for (Resource member : members.values())
		{
			if (member instanceof Directory)
			{
				((Directory) member).accept(visitor);
			}
			else if (member instanceof File)
			{
				visitor.visitFile((File) member);
			}
		}
	}

	@Override
	public String toString()
	{
		return getPath();
	}

}
